package br.com.websec.web;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import br.com.websec.usuario.Usuario;
import br.com.websec.usuario.UsuarioRN;

@ManagedBean(name = "contextoBean")
@SessionScoped
public class ContextoBean {
	

	
	private Usuario usuarioLogado = null;
		
	public Usuario getUsuarioLogado() {
		
		FacesContext context = FacesContext.getCurrentInstance();
		ExternalContext external = context.getExternalContext();
		String email = external.getRemoteUser();
		
		if (this.usuarioLogado == null || !email.equals(this.usuarioLogado.getEmail())) {
			
			if (email != null) {
				
				UsuarioRN usuarioRN = new UsuarioRN();
				this.usuarioLogado = usuarioRN.buscarPorLEmail(email);
				
			}
			
		}
		
		return this.usuarioLogado;
		
	}
	public String UsuarioLogout() {  
        FacesContext fc = FacesContext.getCurrentInstance();  
        HttpSession session = (HttpSession)fc.getExternalContext().getSession(false);  
  
        //expira a sessão  
        session.invalidate();  
  
        FacesContext context = FacesContext.getCurrentInstance();    
        context.getExternalContext().getSessionMap().remove("user");    
          
        System.out.println("Logout!");  
        System.out.println("Sobrou alguém na sessão? >>> " + FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("user"));  
          
        return "toLogin";     
    }  
	
	
	public void setUsuarioLogado(Usuario usuario) {
		
		this.usuarioLogado = usuario;
		
	}
	

}
